//
//  leetcode.cpp
//  DataStructure
//
//  Created by 劢克科技 on 2020/8/3.
//  Copyright © 2020 Shuleiming. All rights reserved.
//

#include "leetcode.hpp"

// 竖式相加法
char * addStrings(char * num1, char * num2)
{
    int i = (int)strlen(num1) - 1, j = (int)strlen(num2) - 1; // 指向最后一位
    int overflow = 0; // 是否需要进位
    int length = i > j ? i + 3 : j + 3; // 返回字符串的长度
    int k = 0; // 指向返回字符串第一位
    char *num = (char*)malloc(sizeof(char) * length);
    
    while (i >= 0 || j >= 0 || overflow > 0) {
        int x = i >= 0 ? num1[i] - '0' : 0;
        int y = j >= 0 ? num2[j] - '0' : 0;
        int sum = x + y + overflow;
        num[k++] = sum % 10 + '0';
        overflow = sum / 10;
        i--;j--;
    }
    for (int i = 0; i < k / 2; i++) { // 将数字逆转
        int t = num[i];
        num[i] = num[k-i-1];
        num[k-i-1] = t;
    }
    num[k] = 0;
    return num;
}

// 两数相加
int* twoSum(int* nums, int numsSize, int target, int* returnSize){
    for (int i = 0; i < numsSize; i++) {
        for (int j = i + 1; j < numsSize; j++) {
            int sum = nums[i] + nums[j];
            if (sum == target) {
                int *arr = (int*)malloc(sizeof(int) * 2);
                arr[0] = i;
                arr[1] = j;
                *returnSize = 2;
                return arr;
            }
        }
    }
    return NULL;
}
